Categories
Node.js Tips

Node.js Tips — Send Emails, Hashing, Promises, and Express Project Structure

Spread the love

Like any kind of apps, there are difficult issues to solve when we write Node apps.

In this article, we’ll look at some solutions to common problems when writing Node apps.

async/await Implicitly Returns Promise

Async functions implicitly return promises.

For instance, if we have:

`const` increment = `async (num) => {
  return num + 1;
}`

Then that returns a promise with num increased by 1.

This means that we can use it by writing:

increment(2)
  .then(num => console.log(num))

If we pass in 2 to increment then num in the callback should be 3.

Get the SHA1 Hash of a String in Node.js

We can get the SHA1 hash of a string by using the crypto module.

For instance, we can write:

const crypto = require('crypto');
const sha = crypto.createHash('sha1');
sha.update('foo');
sha.digest('hex');

We call update with the text that we want to hash.

And call digest to return the hashed hex string.

However, since SHA1 isn’t very secure, we should create SHA256 hashes instead:

const crypto = require('crypto');
crypto.createHash('sha256').update('foo').digest('hex');

We call createHash with 'sha256' to create the SHA256 hash.

The rest is the same.

Make Axios Send Cookies in its Requests Automatically

We can make Axios send cookies in its requests with the withCredentials option.

For instance, we can write:

axios.get('/api/url', { withCredentials: true });

We just set it to true so that we can send the cookie.

Nodemailer with Gmail

We can send emails with Nodemailer with a Gmail SMTP server.

For instance, we can write:

const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');

const transporter = nodemailer.createTransport(smtpTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
  auth: {
    user: 'email@gmail.com',
    pass: 'password'
  }
}));

const mailOptions = {
  from: 'email@gmail.com',
  to: 'friend@example.com',
  subject: 'Hello Email',
  text: 'hello friend'
};

transporter.sendMail(mailOptions, (error, info) => {
  if (error) {
    console.log(error);
  }
  else {
    console.log(info.response);
  }
});

We call the createTransport method to create a transporter object to let us send emails.

We pass in the SMTP server address, set the server to 'gmail' , and pass in the user name and address of our Gmail account.

Then we can set out mail options by setting the from and to emails, subject, and text , which is the content.

Finally, we call sendMail on transporter with the mailOptions to send the email.

The callback is called when it’s done.

error has the error and info has the result of sending the email.

Swap Key with Value JSON

We can swap the key with the value of an object.

To do that, we can use the Object.keys and the for-of loop.

For instance, we can write:

const result = {};
for (const key of `Object.keys(obj)`){
   result[`obj`[key]] = key;
}

We get the keys with Object.keys and then put the values of obj as the key of result and put the key as their values.

Structure an Express Application

To structure an Express app, we can put our production code in the app folder in the root level.

Then inside it, we have the controllers folder for the controllers.

models folder can have the models.

views foder have the views.

test folder is in the root and have the tests.

Inside it, we have the models and views folders for the tests of each kind of code.

Node.js ES6 Classes with require

We can export the class that we want to require by exporting it:

animal.js

class Animal {
  //...
}
module.exports = Animal;

Then we can write:

app.js

const Animal = require('./Animal');
const animal = new Anima();

We require the animal module and use the class.

Placement of catch Before or After then in a Promise Chain

If we have a chain of promises, then we can place the catch method anywhere we want to catch rejected promises.

However, if we place them earlier, then if the promises that come after it are rejected, then it the error won’t be caught by catch .

However, if we put catch earlier, then the later promises can continue until one of the ones that come later are rejected.

Conclusion

We can place the catch method anywhere we want, but they may catch different errors depending on location.

Axios can send cookies with the withCredentials option.

We can swap keys and values of an object by getting the keys and values and swap them.

Nodemailer can be used to send emails.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *